import { Icon } from '@tarojs/components';
import Taro from '@tarojs/taro';
// import { BasePage } from '@components/base-page';
import { GLOBAL_DATA } from '@common/global-data';
import { IDefaultGlobalData } from '@common/interfaces/common';
import vcode, { TrackPage } from "@utils/wx.security.esm";
import fingerprintjs from 'fingerprintjs2'
let ApiStatus = false
import { code } from '@utils/config'
import CryptoJS from 'crypto-js';


/**
 * 获取当前页面page
 */
export function getTopPage(): Taro.Page {
    /** 刷新当前页面*/
    const pages: Array<Taro.Page> = Taro.getCurrentPages() as any; //获取当前页面信息
    return pages[pages.length - 1] as any;
}

export function setGlobalData<T extends IDefaultGlobalData>(data: Partial<T>) {
    Object.assign(GLOBAL_DATA, data);
}

export function setStorage(storageName: string, data: any) {
    Taro.setStorageSync(storageName, data)
}
export function getStorage(storageName: string) {
    return Taro.getStorageSync(storageName)
}

export function getAppData<T extends IDefaultGlobalData>(): T {
    return GLOBAL_DATA || ({} as T);
}
export function debounce(fn: Function, delay = 300) {
    let timer;
    return function (...rest) {
        let context = this;
        let args = rest;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    };
}
export function getUserId() {
    fingerprintjs.get(function (components) {
        const values = components.map(function (component, index) {
            if (index === 0) { //把微信浏览器里UA的wifi或4G等网络替换成空,不然切换网络会ID不一样
                return component.value.replace(/\bNetType\/\w+\b/, '')
            }
            return component.value
        })
        // 生成最终id murmur 
        const murmur = fingerprintjs.x64hash128(values.join(''), 31)
        setStorage('temporaryUserId', murmur)
    })
}

export function checkedLoginStatus() {
    return !!Taro.getStorageSync('Authorization') ? 'Bearer ' + Taro.getStorageSync('Authorization') : ''
}

export function getUserInfoId() {
    return Taro.getStorageSync('userInfo')?.uid || ''
}
export function getLoginAlert() {
    Taro.navigateTo({
        url: '/modules/pages/login/index'
    })
}
export function Toast(title, icon, duration = 3000) {
    Taro.showToast({
        title: title,
        icon: icon,
        duration: duration
    })
}
export function iQOOLog(LogParams, type) {
    // return false
    if (type == 'trace') {
        vcode.trace(LogParams);
    } else {
        vcode.send(LogParams);
    }

    // console.log('埋点信息：', LogParams)
}

/** 时间格式转换
 * @param e 要转换的日期(如：Sat Nov 26 2022 21:37:29 GMT+0800 (中国标准时间))
 * @returns {string} 转换结果(如：2022-11-26 21:37:29)
 */
export function timeFormatConvert(e) {
    const Y = e.getFullYear(); // 年
    const M = prefixZero(e.getMonth() + 1); // 月
    const D = prefixZero(e.getDate()); // 日
    const H = prefixZero(e.getHours()); // 时
    const Mi = prefixZero(e.getMinutes()); // 分
    const S = prefixZero(e.getSeconds()); // 秒
    return Y + "/" + M + "/" + D + " " + H + ":" + Mi + ":" + S;
}
function prefixZero(num = 0, n = 2) {
    // 数字位数不够，数字前面补零
    return (Array(n).join("0") + num).slice(-n);
}
//生成uuid
export function getUuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
            v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}



function padToFixedLength(encryptedValue, length) {
    if (encryptedValue.length >= length) {
        return encryptedValue.slice(0, length);
    }
}

export function encrypt(number, key) {
    const encrypted: any = [];
    const digits = number.toString().split("");

    for (let i = 0; i < digits.length; i++) {
        const digit = digits[i];
        const keyDigit = key[i % key.length];
        const encryptedDigit = (parseInt(digit) + keyDigit) % 10;
        encrypted.push(encryptedDigit.toString());
    }

    return padToFixedLength(encrypted.join(""), digits.length);
}

// 鉴权
export function authorization(method, path, query) {
    let timestamp = Math.floor(Date.now() / 1000),
        queryString = method == 'GET' ? getQueryString(query) : '',
        http_payload = method == 'GET' ? '' : JSON.stringify(query),
        appid = '1002',
        appsecret = code,
        strToSign = method + '&' + path + '&' + queryString + '&' + http_payload + '&appid=' + appid + '&timestamp=' + timestamp,
        signature = hmacSHA2562(appsecret, strToSign);

    let returnValue = 'appid=1002' + ',timestamp=' + timestamp + ',signature=' + signature
    // console.log({
    //     timestamp: timestamp,
    //     queryString: queryString,
    //     method: method,
    //     path: path,
    //     http_payload: http_payload,
    //     appid: appid,
    //     appsecret: appsecret,
    //     returnValue: returnValue,
    //     strtosign: strToSign,
    //     signature: signature
    // })
    return returnValue;
}



function reorderJson(jsonString) {
    const jsonObject = jsonString;
    function sortKeys(obj) {
        if (typeof obj !== 'object' || obj === null) {
            return obj;
        }
        if (Array.isArray(obj)) {
            return obj.map(sortKeys);
        }
        const sortedKeys = Object.keys(obj).sort();
        const sortedObj = {};
        sortedKeys.forEach(key => {
            sortedObj[key] = sortKeys(obj[key]);
        });
        return sortedObj;
    }
    const reorderedObject = sortKeys(jsonObject);
    const reorderedJsonString = JSON.stringify(reorderedObject);
    return reorderedJsonString;
}
function getQueryString(query) {
    // 对 query 对象的键进行 ASCII 升序排序
    const sortedKeys = Object.keys(query).sort();

    // 构建处理后的 query 字符串
    let processedQuery = '';
    for (let key of sortedKeys) {
        // 对键和值进行 URL 编码
        const encodedKey = encodeURIComponent(key);
        const encodedValue = encodeURIComponent(query[key]);

        // 拼接处理后的键值对
        processedQuery += `${encodedKey}=${encodedValue}&`;
    }

    // 去除末尾的多余的 '&' 符号
    processedQuery = processedQuery.slice(0, -1);

    return processedQuery
}

function hmacSHA2562(key, data) {
    let hash = CryptoJS.HmacSHA256(data, key);
    let hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
    return hashInBase64;
}
function decrypt(encryptedNumber, key) {
    const decrypted: any = [];
    const digits = encryptedNumber.split("");
    for (let i = 0; i < digits.length; i++) {
        const digit = digits[i];
        const keyDigit = key[i % key.length];
        let decryptedDigit = parseInt(digit) - keyDigit;
        if (decryptedDigit < 0) {
            decryptedDigit += 10; // 处理借位
        }
        decrypted.push(decryptedDigit.toString());
    }
    return parseInt(decrypted.join(""));
}
